import re
import yaml

def read_yaml_config(file_path):
    """
    读取 YAML 配置文件
    :param file_path: 配置文件路径
    :return: 配置信息
    """
    with open(file_path, 'r', encoding='utf-8') as file:
        return yaml.safe_load(file)

def read_input_file(file_path):
    """
    读取输入文件内容
    :param file_path: 输入文件路径
    :return: 文件内容
    """
    with open(file_path, 'r', encoding='utf-8') as file:
        return file.read()

def insert_line_breaks(text, keywords):
    """
    根据关键字插入换行符
    :param text: 输入文本
    :param keywords: 换行关键字列表
    :return: 处理后的文本
    """
    pattern = '|'.join(keywords)
    return re.sub(pattern, r'\n\g<0>', text)

def remove_leading_trailing_whitespace(text):
    """
    去掉每行首尾的空格和制表符
    :param text: 输入文本
    :return: 处理后的文本
    """
    lines = text.splitlines()
    # 去除每行首尾的空格和制表符
    trimmed_lines = [line.strip() for line in lines]
    # 重新组合成文本
    return '\n'.join(trimmed_lines)

def write_output_file(file_path, text):
    """
    将处理后的文本写入输出文件
    :param file_path: 输出文件路径
    :param text: 处理后的文本
    """
    with open(file_path, 'w', encoding='utf-8') as file:
        file.write(text)

def main():
    # 读取配置文件
    config = read_yaml_config('pre_book_mark.yml')
    keywords = config.get('keywords', [])

    # 读取输入文件
    input_text = read_input_file('book_mark_pre_in.txt')

    # 插入换行符
    output_text = insert_line_breaks(input_text, keywords)

    # 去掉每行首尾的空格和制表符
    output_text = remove_leading_trailing_whitespace(output_text)

    # 写入输出文件
    write_output_file('book_mark_in.txt', output_text)

if __name__ == "__main__":
    main()